//
//  ZYHouseViewModel.m
//  YiLin
//
//  Created by Zyark on 2018/6/15.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYHouseViewModel.h"
#import "ZYLoadMoreViewModel.h"
#import "ZYHouse.h"
#import "ZYUser.h"
#import "AFNetWorkUtils.h"

@interface ZYHouseViewModel()
/**修改住宅类型*/
typedef NS_ENUM(NSInteger,ZYHouseViewModelModifyType){
    /**添加住宅*/
    ZYHouseViewModelModifyTypeAdd =0,
    /**住宅编辑*/
    ZYHouseViewModelModifyTypeEdit
};
@property(nonatomic,strong) ZYLoadMoreViewModel *loadViewModel;

/**
 添加住宅
 */
@property(nonatomic,strong) RACCommand *addCommand;

/**
 修改住宅
 */
@property(nonatomic,strong) RACCommand *modifyCommand;

/**
 删除住宅
 */
@property(nonatomic,strong) RACCommand *deleteCommand;

/**
 首页住宅列表
 */
@property(nonatomic,strong) RACCommand *indexHouseCommand;
@end

@implementation ZYHouseViewModel
//上拉加载更多，下拉刷新
-(ZYLoadMoreViewModel *)loadViewModel{
    if(!_loadViewModel){
        _loadViewModel = [[ZYLoadMoreViewModel alloc] init];
        ZYUser *user = [ZYConfig userInfo];
        NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOUSE_LIST_URL];
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"10",@"pageSize",@"1",@"page",nil];
        [params setObject:user.token forKey:@"ssid"];
        _loadViewModel.clazz = [ZYHouse class];
        _loadViewModel.params = params;
        _loadViewModel.url = url;
        _loadViewModel.sourceArray = [NSMutableArray array];
        _sourceCommand = _loadViewModel.sourceCommand;
    }
    return _loadViewModel;
}

-(RACCommand *)sourceCommand{
    if(!_sourceCommand){
        _sourceCommand = self.loadViewModel.sourceCommand;
    }
    return _sourceCommand;
}

-(RACCommand *)addCommand{
    if(!_addCommand){
        _addCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doSaveHouse:input type:ZYModifyHouseTypeAdd subscriber:subscriber];
                return nil;
            }];
        }];
    }
    return _addCommand;
}

-(RACCommand *)indexHouseCommand{
    if(!_indexHouseCommand){
        _indexHouseCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_INDEX_HOUSE_LIST_URL];
            NSString *token = [ZYConfig loginToken];
            return [[AFNetWorkUtils racPOSTWithURL:url params:@{@"ssid":token}] map:^id(id value) {
                NSDictionary *data = value;
                NSDictionary *result = [data objectForKey:@"result"];
                NSArray *row = [result objectForKey:@"rows"];
                if(!row){
                    return [NSMutableArray array];
                }
                return [NSArray modelArrayWithClass:[ZYHouse class] json:row];
            }];
        }];
    }
    return _indexHouseCommand;
}

-(RACCommand *)deleteCommand{
    if(!_deleteCommand){
        _deleteCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            ZYUser *user = [ZYConfig userInfo];
            NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOUSE_DELETE_URL];
            NSString *houseId = input;
            NSDictionary *params = @{@"ssid":user.token,@"houseId":houseId};
            RACSignal *netSignal = [[AFNetWorkUtils racDeleteWithURL:url isJSON:YES params:params] map:^id(id value) {
                return [NSNumber numberWithBool:YES];
            }];
            return netSignal;
        }];
    }
    return _deleteCommand;
}

-(RACCommand *)modifyCommand{
    if(!_modifyCommand){
        _modifyCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            @weakify(self);
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
                @strongify(self);
                [self doSaveHouse:input type:ZYModifyHouseTypeEdit subscriber:subscriber];
                return nil;
            }];
        }];
    }
    return _modifyCommand;
}

-(void)doSaveHouse:(ZYHouse *)house type:(ZYModifyHouseType)type subscriber:(id<RACSubscriber>)subscriber{
    BOOL success = [self checkAddData:subscriber withHouse:house type:type];
    if(!success){
        return;
    }
    //校验数据
    NSString *token = [ZYConfig loginToken];
    NSString *url = @"";
    NSDictionary *params;
    if(type == ZYModifyHouseTypeAdd){
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOUSE_ADD_URL];
        params = @{@"name":house.name,@"address":house.address,@"lng":house.longitude,@"lat":house.latitude,@"isManage":[NSNumber numberWithBool:house.isManage],@"ssid":token};
    }else{
        url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOUSE_MODIFY_URL];
        params = @{@"name":house.name,@"address":house.address,@"lng":house.longitude,@"lat":house.latitude,@"isManage":[NSNumber numberWithBool:house.isManage],@"id":[NSNumber numberWithInteger:house.houseId],@"ssid":token};
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer new];
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [acceptableContentTypes addObject:@"text/plain"];
    [acceptableContentTypes addObject:@"text/html"];
    manager.responseSerializer.acceptableContentTypes = acceptableContentTypes;
    //    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"multipart/form-data; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager POST:url
       parameters:params
        constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (house.imageData) {
            [formData appendPartWithFileData:house.imageData
                                        name:@"image"
                                    fileName:@"img.jpg"
                                    mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *code = [responseObject objectForKey:@"code"];
        if([code integerValue] !=200){
            if([code integerValue] == 301){
                [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:LOGIN_FAILURE]];
                return;
            }
            NSString *errorMessage = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:[NSString stringWithFormat:@"code_%@",code]];
            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:errorMessage]];
            [subscriber sendCompleted];
        }else{
            //返回住宅信息
            ZYHouse *house = [ZYHouse modelWithJSON:[responseObject objectForKey:@"result"]];
            if([[ZYConfig houseId] integerValue] == house.houseId && !house.isManage){
                [ZYConfig setHouseId:@""];//清空住宅id
                [ZYConfig setIsAtHome:NO];
            }
            if((NULLString([ZYConfig houseId]) || [[ZYConfig houseId] isEqualToString:@"0"]) && house.isManage){
                [ZYConfig setHouseId:[NSString stringWithFormat:@"%ld",(long)house.houseId]];
            }
            [subscriber sendNext:house];
            [subscriber sendCompleted];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [subscriber sendError:error];
        [subscriber sendCompleted];
    }];

}


//检查数据
-(BOOL)checkAddData:(id<RACSubscriber>)subscriber withHouse:(ZYHouse *)house type:(ZYModifyHouseType)type{
    if(NULLString(house.name)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_HOUSE_NAME_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
    if(NULLString(house.address)){
        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_ADDRESS_EMPTY]]];
        [subscriber sendCompleted];
        return NO;
    }
//    if(type == ZYModifySubAccountTypeAdd){

//    }else{
//        if(NULLString(user.oldPassword)){
//            [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_OLD_PASSWORD_EMPTY]]];
//            [subscriber sendCompleted];
//            return NO;
//        }
//    }
//    if(NULLString(user.password)){
//        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_PASSWORD_EMPTY]]];
//        [subscriber sendCompleted];
//        return NO;
//    }
//    if(![user.password isEqualToString:user.rePassword]){
//        [subscriber sendError:[NSErrorHelper createErrorWithErrorInfo:[self.language getStringByKey:LC_ERROR_INCONSISTENT_PASSWORD]]];
//        [subscriber sendCompleted];
//        return NO;
//    }
    return YES;
}

-(void)setupParams{
    ZYUser *user = [ZYConfig userInfo];
    NSString *url = [NSString stringWithFormat:@"%@%@",ZYAPI_BASE_URL,ZYAPI_HOUSE_LIST_URL];
    NSMutableDictionary *params = _loadViewModel.params;
    [params setObject:user.token forKey:@"ssid"];
    _loadViewModel.params = params;
    _loadViewModel.url = url;
}

-(void)loadNewHouseList{
    [self setupParams];
    [self.loadViewModel loadNewData];
}

-(void)loadMoreHouseList{
    [self setupParams];
    [self.loadViewModel.params setObject:[NSNumber numberWithInteger:self.loadViewModel.pageNum +1] forKey:@"page"];
    [self.loadViewModel loadNextPageData];
}

-(void)addHouse:(ZYHouse *)house{
    [self.addCommand execute:house];
}

-(void)modifyHouse:(ZYHouse *)house{
    [self.modifyCommand execute:house];
}

-(void)deleteHouse:(NSString *)houseId{
    [self.deleteCommand execute:houseId];
}
@end
